import { defineStore } from "pinia";

import { loginApi } from "@/api/auth";
// import { getUserInfoApi } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";

import { LoginData } from "@/api/auth/types";
import { UserInfo } from "@/api/user/types";

import { useStorage } from "@vueuse/core";

export const useUserStore = defineStore("user", () => {
  const user: UserInfo = {
    roles: [],
    perms: [],
  };

  const token = useStorage("accessToken", "");
  // 用户id
  const userId = useStorage("userId", "");
  const userName = useStorage("userName", "");
  // 企业信息
  const Information = useStorage<any>("Information", "");
  // 企业id
  const oid = useStorage<any>("oid", "");
  // 企业机构刷新
  const oidRefresh = ref<number>(0);
  const oidRefreshChange = (val: number) => {
    oidRefresh.value = 0;
    oidRefresh.value = val;
  };
  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    // response: { data: { tokenType: any; accessToken: any; }; }
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((res: any) => {
          // const { tokenType, accessToken } = res;
          // token.value = tokenType + " " + accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          const { result } = res;
          token.value = result.uid;
          userId.value = result.uid;
          userName.value = result.userName;
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 模拟登录
   * @param {LoginData}
   * @returns
   */
  const simulationLogin = () => {
    return new Promise<void>((resolve) => {
      token.value = "1";
      userId.value = "1";
      oid.value = "26";
      userName.value = "超级管理员";
      Information.value = JSON.stringify({
        tel: "16878895665",
        oid: 26,
        org_name: "阿里巴巴",
        addr: "杭州西湖",
        contacts: "马某",
      });
      resolve();
    });
  };

  // oid 企业信息
  function institution(row: any) {
    oid.value = row.oid;
    Information.value = JSON.stringify(row);
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      // 动态mock
      // getUserInfoApi()
      //   .then(({ data }) => {
      //     if (!data) {
      //       reject("Verification failed, please Login again.");
      //       return;
      //     }
      //     if (!data.roles || data.roles.length <= 0) {
      //       reject("getUserInfo: roles must be a non-null array!");
      //       return;
      //     }
      //     Object.assign(user, { ...data });
      //     resolve(data);
      //   })
      //   .catch((error: unknown) => {
      //     reject(error);
      //   });

      // 暂时模拟静态
      const data: any = {
        roles: ["ADMIN"],
        perms: [
          "sys:menu:delete",
          "sys:dept:edit",
          "sys:dict_type:add",
          "sys:dict:edit",
          "sys:dict:delete",
          "sys:dict_type:edit",
          "sys:menu:add",
          "sys:user:add",
          "sys:role:edit",
          "sys:dept:delete",
          "sys:user:edit",
          "sys:user:delete",
          "sys:user:reset_pwd",
          "sys:dept:add",
          "sys:role:delete",
          "sys:dict_type:delete",
          "sys:menu:edit",
          "sys:dict:add",
          "sys:role:add",
        ],
      };
      Object.assign(user, { ...data });
      resolve(data);
    });
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      token.value = "";
      userId.value = "";
      userName.value = "";
      Information.value = "";
      oid.value = "";
      location.reload(); // 清空路由
      resolve();

      // logoutApi()
      //   .then(() => {
      //     token.value = "";
      //     userId.value = "";
      //     userName.value = "";
      //     Information.value = "";
      //     oid.value = "";
      //     location.reload(); // 清空路由
      //     resolve();
      //   })
      //   .catch(() => {
      //     token.value = "";
      //     userId.value = "";
      //     userName.value = "";
      //     Information.value = "";
      //     oid.value = "";
      //     location.reload(); // 清空路由
      //     // resolve();
      //   });
    });
  }

  // remove token
  function resetToken() {
    return new Promise<void>((resolve) => {
      token.value = "";
      resetRouter();
      resolve();
    });
  }

  return {
    token,
    user,
    login,
    getUserInfo,
    logout,
    resetToken,
    institution,
    Information,
    userName,
    oidRefresh,
    oidRefreshChange,
    simulationLogin
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
